import Request from './luch-request/index.js'
import {
	useUserStore
} from '@/stores/user'
const {
	onLogOut
} = useUserStore()
const defaultRequestInterceptors = (config) => {
	const {
		getToken,
		isLogin
	} = useUserStore()
	config.data && (config.data = Object.assign(config.data))
	if (isLogin()) {
		config.header = {
			...config.header,
			token: getToken()
		}
	}
	return config
}
const defaultResponseInterceptors = (response) => {
	if (response.data.code == 200) {
		return response.data
	} else if (response.data.code === 401) {
		onLogOut();
		return Promise.reject(response.data);
	}
	return Promise.reject(response.data);
}

export const request = (options) => {
	const http = new Request()
	http.interceptors.request.use(defaultRequestInterceptors, (error) => {
		return Promise.reject(error)
	})
	http.interceptors.response.use(defaultResponseInterceptors, (error) => {
		return Promise.reject(error)
	})
	return http
}